package com.hmdp.controller;


import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Slf4j
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        // 先查缓存
        List<ShopType> cacheShopList = new ArrayList<>();
        Long size = stringRedisTemplate.opsForList().size("shop-type");
        log.info("size:{}", size);
        if (size!=0){
            for (Long i = Long.valueOf(0); i < size; i++) {
                // log.info("shop type from cache-------->:{}", stringRedisTemplate.opsForList().index("shop-type", i));
                cacheShopList.add(JSONUtil.toBean(stringRedisTemplate.opsForList().index("shop-type", i), ShopType.class));
            }
            return Result.ok(cacheShopList);
        }
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();

        // 保存缓存
        typeList = typeList.stream().map(
                (item) -> {stringRedisTemplate.opsForList().rightPush("shop-type", JSONUtil.toJsonStr(item));
                    log.info("saving----------->{}", item);
                return item;}
        ).collect(Collectors.toList());
        stringRedisTemplate.expire("shop-type", CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
